<?php
declare(strict_types=1);

namespace app\api\service;

use app\common\model\GroupModel;
use app\common\model\WaterModel;
use app\common\traits\CacheTrait;
use think\Response;

class FriendService extends CommonService
{
    use CacheTrait;

    public function friendData(array $params)
    {
        if ($params['type'] == 1) {//纯文字处理
            switch ($params['msg']) {
                case '喝水提醒':
                    return (new WaterService())->water($params);
                case '关闭喝水提醒':
                    return (new WaterService())->cancelWater($params);
                case '帮助':
                    return $this->getHelp($params);
                case '我要购买':
                    return $this->wxPay($params);
                case '人工客服':
                    return $this->getKf($params);
                case '转发群':
                    return $this->sendGroup($params, 1);
                case '转发私聊':
                    return $this->sendGroup($params, 2);
                case '转发全部':
                    return $this->sendGroup($params, 3);
                case '关闭转发':
                    return $this->sendGroup($params, 4);
                case '设置文案':
                    return $this->sendText($params);
                case '关键词设置':
                    return $this->sendGroupContent($params);
                case '关键词清理':
                    return $this->outGroupContent($params);
//                case '抖音视频':
//                    return (new ShortUrlService())->getDyVideo($params);
                default://进群业务
                    $ret = (new GroupService())->invitationGroup($params);
                    if ($ret) return $ret;
            }
            $this->sendAllMessage($params);
            $this->addTextContent($params);
            $this->addGroupContent($params);
            $this->sendFAllMessage($params);
            $this->errMessage($params);
        } elseif ($params['type'] == 2003) {//邀请机器人进群
            (new GroupService())->agreeGroupInviteData($params);
        }
    }

    private function outGroupContent($params){
        if ($params['final_from_wxid'] === env("master_id")) {
            $this->delCache('f_key_message','g_key_message');
            return $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], '清理完成');
        }
    }

    public function sendGroupContent($params)
    {
        $this->setCache("robot_set_group_content", 1, 60);
        return $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], "添加关键词回复指令开启，
        请在60秒内发送官关键词组合！\r 例如：群聊-你好|我很好,私聊-在吗|在的  \r特别提醒：注意格式，错误请回复删除关键词 会删除所有关键词 谨慎使用!");
    }

    public function sendFAllMessage($params,$type = 1){
        $wxid = $params['final_from_wxid'];
        if($type === 1){
            $dd = $this->getCache("f_key_message");
            if(!$dd) return;
            $res = json_decode($dd,true)??[];
        }else{
            $wxid = $params['from_wxid'];
            $dd = $this->getCache("g_key_message");
            if(!$dd) return;
            $res = json_decode($dd,true)??[];
        }
        if(!$res) return;

        foreach ($res as $v){
            if($v['keys'] === $params['msg']){
                if($type == 1){
                    sleep(rand(1,2));
                }
                $this->send_text_msg($params['robot_wxid'], $wxid, $v['vue']);
                exit();
            }
        }
    }

    public function addGroupContent($params)
    {
        $ret = $this->getCache("robot_set_group_content");
        if ($ret) {
            if ($params['final_from_wxid'] === env("master_id")) {
                $msg = $params['msg'];
                $gArray = [];
                $fArray = [];
                if(!$msg){
                    $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], "消息空，请从新发送");exit();
                }
                //群聊-你好|我很好,私聊-在吗|在的
                $arr1 = explode(',',$msg);
                if(count($arr1) <= 1){//一条 直接处理
                    $arr2 = explode("-",$arr1[0]);
                    $this->pageContent($arr2,$gArray,$fArray);
                }else{//多条循环处理
                    foreach ($arr1 as $k=> $v){
                        $arr2 = explode("-",$v);

                        $this->pageContent($arr2,$gArray,$fArray);
                    }
                }

                $a1 = $this->getCache("g_key_message");
                if($a1){
                    $a1 = json_decode($a1,true)??[];
                    $a1 = array_merge($gArray,$a1);
                }else{
                    $a1 = $gArray;
                }

                $a2 = $this->getCache("f_key_message");
                if($a2){
                    $a2 = json_decode($a2,true)??[];
                    $a2 = array_merge($fArray,$a2);
                }else{
                    $a2 = $fArray;
                }
                $this->setCache('g_key_message',json_encode($a1));
                $this->setCache('f_key_message',json_encode($a2));
                $this->delCache("robot_set_group_content");
                $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], "设置关键词完成，关闭指令！");exit();
            }
        }
    }

    private function pageContent($arr2,&$gArray,&$fArray){
        $arr3 = explode("|", $arr2[1] ?? '');

        if($arr2[0] === "群聊"){
            $gArray[] = ['keys' => $arr3[0] ?? '', 'vue' => $arr3[1] ?? ''];
        }else{
            $fArray[] = ['keys' => $arr3[0] ?? '', 'vue' => $arr3[1] ?? ''];
        }
    }

    public function addTextContent($params)
    {
        $ret = $this->getCache("set_text_content");
        if ($ret) {
            if ($params['final_from_wxid'] === env("master_id")) {
                $message = trim($params['msg']);
                $this->setCache("add_friend_message", json_encode($message));
                $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], '存储完成！指令关闭！');
                $this->delCache("set_text_content");
                exit();
            } else {
                $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], '无此命令权限，请联系客服wx:poison_robot！');
                exit();
            }
        }

    }

    public function sendText($params)
    {
        if ($params['final_from_wxid'] === env("master_id")) {
            $this->setCache("set_text_content", 1, 60);
            $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], '指令已激活，请在60秒内发送文案信息！');
        } else {
            $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], '无此命令权限，请联系客服wx:poison_robot！');
        }
        return true;

    }

    public function sendGroup($params, $number)
    {
        if ($params['final_from_wxid'] === env("master_id")) {
            if ($number == 4) {
                $this->delCache("send_all_message");
                return $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], '指令已关闭');
            }
            $this->setCache("send_all_message", $number, 60);
            return $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], '指令已激活，请发送');
        } else {
            return $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], '您没有权限执行此命令，请联系客服wx:poison_robot');
        }

    }

    public function sendAllMessage($params)
    {
        $num = $this->getCache('send_all_message');
        if (!$num) return false;
        switch ($num) {
            case 1://群聊
                $this->sendGMessage($params);
                break;
            case 2://私聊
                //获取好友列表
                $this->sendFriendMessage($params);
                break;
            case 3://全部
                $this->sendFriendMessage($params);
                $this->sendGMessage($params);
                break;
        }
        exit();
    }

    private function sendGMessage($params)
    {
        $data = (new GroupModel())->where('robot_wxid', $params['robot_wxid'])->select()->toArray();
        foreach ($data as $v) {
            $this->send_text_msg($params['robot_wxid'], $v['wxid'], $params['msg']);
        }
    }

    private function sendFriendMessage($params)
    {
        $data = json_decode($this->get_friend_list($params['final_from_wxid'], 1), true);
        foreach ($data['data'] as $v) {
            $this->send_text_msg($params['robot_wxid'], $v['wxid'], $params['msg']);
        }
    }

    public function sendTextContent($params)
    {
        $msg = $this->getCache('add_friend_message');
        if (!$msg) {
            return false;
        }
        $msg = json_decode($msg, true);
        $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], $msg);
        exit();
    }

    public function addFriend($params)
    {
        sleep(1);
        $this->sendTextContent($params);
        //增加到好友表中 发送自助信息
        $add = "========================\r" .
            "智能小助手 欢迎您～[庆祝]\r" .
            "承接：App/小程序/公众号/ERP/OA/机器人定制\r" .
            "价格美丽，欢迎骚扰~[玫瑰]\r" .
            "========================";
        $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], $add);
        $this->getHelp($params);

    }

    public function errMessage(array $params)
    {
        $message = "========================\r" .
            "暂无识别到有效文字~\r" .
            "--------------------------\r" .
            "承接：App/小程序/公众号/ERP/OA/机器人定制\r" .
            "价格美丽，欢迎骚扰~[玫瑰]\r" .
            "微信号:PoisonGive\r" .
            "--------------------------\r" .
            "输入`帮助`指令 获取更多介绍\r" .
            "========================";
        return $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], $message);
    }

    public function getHelp(array $params)
    {
        $groupModel = new GroupModel();
        $data = $groupModel->getGroupDataByStatus($params);
        $message = "========================\r" .
            "[庆祝][庆祝]请输入下面指令[庆祝][庆祝]\r" .
            "  ---------入群服务--------\r";
        foreach ($data as $v) {
            $message .= "       [爱心]" . $v['nickname'] . "[爱心]\r";
        }
        $message .= "  ---------个人业务--------\r" .
            "       [咖啡]喝水提醒[咖啡]\r" .
            "       [發]我要购买[發]\r" .
            "       [握手]人工客服[握手]\r" .
            "  --------------------------\r" .
            "输入`帮助`指令 获取更多介绍\r" .
            "[庆祝]免费开放自动邀请进群功能\r" .
            "[庆祝]邀请我进群后,设置为管理员\r" .
            "[庆祝]就可以自动拉人进群咯~\r" .
            "========================";
        return $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], $message);
    }

    public function getKf(array $params)
    {
        $message = "========================\r" .
            "客服微信：PoisonGive\r" .
            "--------------------------\r" .
            "客服QQ：130043536\r" .
            "--------------------------\r" .
            "输入`帮助`指令 获取更多介绍\r" .
            "========================";
        return $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], $message);
    }

    public function wxPay(array $params)
    {
        $message = "========================\r" .
            "大众版限时免费开放~\r" .
            "--------------------------\r" .
            "期待邀请我进群哦~\r" .
            "--------------------------\r" .
            "如需定制 请输入`人工客服`\r" .
            "--------------------------\r" .
            "输入`帮助`指令 获取更多介绍\r" .
            "========================";
        return $this->send_text_msg($params['robot_wxid'], $params['final_from_wxid'], $message);
    }

}